const router = require('koa-router')();
const { pool } = require('../config/database');
const { authMiddleware, optionalAuthMiddleware } = require('../middleware/auth');

router.prefix('/api/music');

// 获取轮播图
router.get('/banners', async (ctx) => {
  try {
    const [banners] = await pool.execute(
      'SELECT banner_id, image_url, title, link_url FROM banners WHERE status = 1 ORDER BY sort_order ASC'
    );

    ctx.body = {
      code: 200,
      message: '获取轮播图成功',
      data: banners
    };
  } catch (error) {
    console.error('获取轮播图失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取推荐歌曲
router.get('/recommended', optionalAuthMiddleware, async (ctx) => {
  try {
    const [songs] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count,
             a.name as artist_name, a.avatar_url as artist_avatar,
             al.name as album_name, al.cover_image_url as album_cover
      FROM recommended_songs rs
      JOIN songs s ON rs.song_id = s.song_id
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE s.status = 1
      ORDER BY rs.sort_order ASC
    `);

    ctx.body = {
      code: 200,
      message: '获取推荐歌曲成功',
      data: songs
    };
  } catch (error) {
    console.error('获取推荐歌曲失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取热门歌曲
router.get('/hot', optionalAuthMiddleware, async (ctx) => {
  try {
    const [songs] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count,
             a.name as artist_name, a.avatar_url as artist_avatar,
             al.name as album_name, al.cover_image_url as album_cover
      FROM hot_songs hs
      JOIN songs s ON hs.song_id = s.song_id
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE s.status = 1
      ORDER BY hs.sort_order ASC
    `);

    ctx.body = {
      code: 200,
      message: '获取热门歌曲成功',
      data: songs
    };
  } catch (error) {
    console.error('获取热门歌曲失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 搜索歌曲
router.get('/search', optionalAuthMiddleware, async (ctx) => {
  try {
    const { keyword, page = 1, limit = 20 } = ctx.query;
    
    if (!keyword) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '搜索关键词不能为空'
      };
      return;
    }

    const offset = (page - 1) * limit;
    
    const [songs] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count,
             a.name as artist_name, a.avatar_url as artist_avatar,
             al.name as album_name, al.cover_image_url as album_cover
      FROM songs s
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE s.status = 1 AND (s.name LIKE ? OR a.name LIKE ?)
      ORDER BY s.play_count DESC
      LIMIT ? OFFSET ?
    `, [`%${keyword}%`, `%${keyword}%`, parseInt(limit), parseInt(offset)]);

    // 记录搜索历史（如果用户已登录）
    if (ctx.user) {
      await pool.execute(
        'INSERT INTO search_history (user_id, keyword) VALUES (?, ?)',
        [ctx.user.userId, keyword]
      );
    }

    ctx.body = {
      code: 200,
      message: '搜索成功',
      data: songs
    };
  } catch (error) {
    console.error('搜索失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取歌曲详情
router.get('/song/:id', optionalAuthMiddleware, async (ctx) => {
  try {
    const songId = ctx.params.id;
    
    const [songs] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count, s.lyrics,
             a.name as artist_name, a.avatar_url as artist_avatar, a.description as artist_description,
             al.name as album_name, al.cover_image_url as album_cover, al.release_date, al.description as album_description
      FROM songs s
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE s.song_id = ? AND s.status = 1
    `, [songId]);

    if (songs.length === 0) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '歌曲不存在'
      };
      return;
    }

    // 增加播放次数
    await pool.execute(
      'UPDATE songs SET play_count = play_count + 1 WHERE song_id = ?',
      [songId]
    );

    // 记录播放历史（如果用户已登录）
    if (ctx.user) {
      await pool.execute(
        'INSERT INTO play_history (user_id, song_id) VALUES (?, ?)',
        [ctx.user.userId, songId]
      );
    }

    ctx.body = {
      code: 200,
      message: '获取歌曲详情成功',
      data: songs[0]
    };
  } catch (error) {
    console.error('获取歌曲详情失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 添加收藏
router.post('/favorite', authMiddleware, async (ctx) => {
  try {
    const { songId } = ctx.request.body;
    const userId = ctx.user.userId;

    if (!songId) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '歌曲ID不能为空'
      };
      return;
    }

    // 检查是否已收藏
    const [existing] = await pool.execute(
      'SELECT id FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [userId, songId]
    );

    if (existing.length > 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '歌曲已在收藏列表中'
      };
      return;
    }

    await pool.execute(
      'INSERT INTO user_favorites (user_id, song_id) VALUES (?, ?)',
      [userId, songId]
    );

    ctx.body = {
      code: 200,
      message: '收藏成功'
    };
  } catch (error) {
    console.error('收藏失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 取消收藏
router.delete('/favorite/:songId', authMiddleware, async (ctx) => {
  try {
    const songId = ctx.params.songId;
    const userId = ctx.user.userId;

    await pool.execute(
      'DELETE FROM user_favorites WHERE user_id = ? AND song_id = ?',
      [userId, songId]
    );

    ctx.body = {
      code: 200,
      message: '取消收藏成功'
    };
  } catch (error) {
    console.error('取消收藏失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取用户收藏列表
router.get('/favorites', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.user.userId;

    const [favorites] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count,
             a.name as artist_name, a.avatar_url as artist_avatar,
             al.name as album_name, al.cover_image_url as album_cover,
             uf.create_time as favorite_time
      FROM user_favorites uf
      JOIN songs s ON uf.song_id = s.song_id
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE uf.user_id = ? AND s.status = 1
      ORDER BY uf.create_time DESC
    `, [userId]);

    ctx.body = {
      code: 200,
      message: '获取收藏列表成功',
      data: favorites
    };
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 获取播放历史
router.get('/history', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.user.userId;

    const [history] = await pool.execute(`
      SELECT s.song_id, s.name, s.cover_image_url, s.duration, s.file_url, s.play_count,
             a.name as artist_name, a.avatar_url as artist_avatar,
             al.name as album_name, al.cover_image_url as album_cover,
             ph.play_time
      FROM play_history ph
      JOIN songs s ON ph.song_id = s.song_id
      LEFT JOIN artists a ON s.artist_id = a.artist_id
      LEFT JOIN albums al ON s.album_id = al.album_id
      WHERE ph.user_id = ? AND s.status = 1
      ORDER BY ph.play_time DESC
      LIMIT 50
    `, [userId]);

    ctx.body = {
      code: 200,
      message: '获取播放历史成功',
      data: history
    };
  } catch (error) {
    console.error('获取播放历史失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

// 清除播放历史
router.delete('/history', authMiddleware, async (ctx) => {
  try {
    const userId = ctx.user.userId;

    await pool.execute(
      'DELETE FROM play_history WHERE user_id = ?',
      [userId]
    );

    ctx.body = {
      code: 200,
      message: '清除播放历史成功'
    };
  } catch (error) {
    console.error('清除播放历史失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误'
    };
  }
});

module.exports = router;
